//
//  DatabaseSetting.h
//  KoalaKnow
//
//  Created by sally on 16/1/22.
//  Copyright © 2016年 szjn. All rights reserved.
//

#import "DatabaseSetting.h"
#import <FMDB.h>

static DatabaseSetting *_instance = nil;

@implementation DatabaseSetting

+ (DatabaseSetting *)shareInstance {
  if (!_instance) {
    @synchronized(self) {
      if (!_instance) {
        _instance = [[self alloc] init];
      }
    }
  }
  return _instance;
}

- (NSString *)dbPathWithUserID:(NSString *)userID {
  NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  NSString *path = [NSString stringWithFormat:@"%@/%@.sqlite", docPath, userID];
  return path;
}

- (BOOL)createUserDB:(NSString *)userID {
  FMDatabase *db = [FMDatabase databaseWithPath:[self databaseFilePath]];
  //为数据库设置缓存，提高查询效率
  [db setShouldCacheStatements:YES];
  if (![db open]) {
    NSLog(@"数据库打开失败");
    return NO;
  }
  return YES;
}

- (NSString *)databaseFilePath {
  NSArray *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentPath = [filePath objectAtIndex:0];
  NSLog(@"%@", filePath);
  NSString *dbFilePath = [documentPath stringByAppendingPathComponent:@"data.sqlite"];
  return dbFilePath;
}

- (BOOL)isExistUserDB:(NSString *)userID {
  NSString *path = [self dbPathWithUserID:userID];
  return [[NSFileManager defaultManager] fileExistsAtPath:path];
}

- (void)setShareDatabaseWithUserID:(NSString *)userID {
  NSString *path = [self dbPathWithUserID:userID];
  FMDatabase *database = [FMDatabase databaseWithPath:path];
  self.shareDatabase = database;
}

@end
